package com.eps.security;

import com.eps.core.EpsManager;
import com.eps.dao.daobase;
import com.eps.dao.daointerface;
import org.apache.log4j.Logger;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.*;

public class SecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {

    private PathMatcher urlMatcher = new AntPathMatcher();
    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
    private static final Logger logger = Logger.getLogger(SecurityMetadataSourceImpl.class);

    public SecurityMetadataSourceImpl() throws Exception {
        LoadRes();
        System.out.println("构造MetadataSourceImpl");
    }

    private void LoadRes() {
        if (null==resourceMap)
            resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
        daointerface dbinterface=new daobase();
        List<SecurityMetada> list=dbinterface.findAll(SecurityMetada.class);
        for (SecurityMetada aList : list) {
            Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
            for (String configAttribute : aList.getRole().split(",")) {
                ConfigAttribute ca = new SecurityConfig(configAttribute);
                atts.add(ca);
            }
            resourceMap.put(aList.getUrl(), atts);
        }
        if (logger.isInfoEnabled()) {
            logger.info("资源加载完毕");
        }
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String resUrl = ((FilterInvocation) object).getRequestUrl();
        for (String url : resourceMap.keySet()) {
            if (urlMatcher.match(url, resUrl)) {
                Collection<ConfigAttribute> col = resourceMap.get(url);
                if (logger.isInfoEnabled()) {
                    logger.info("找到了匹配对象");
                }
                return col;
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
